package juc.threadLocal;

/*本例子使用ThreadLocal进行信息传递，解耦项目*/
public class UserContextDemo {
    public static void main(String[] args) {
        /*设置数据场景：在登录鉴权拦截器中，校验完成用户信息后设置
        * request.setAttribute("mid", "Integer.parseInt(mid)");
        *
        * */
        UserContext.getInstance().setContext(new UInfo("tom", 1));
        /*使用场景：在各个业务具体场景下使用*/
        UInfo context = UserContext.getInstance().getContext();
        System.out.println(context.getId());
        System.out.println(context.getName());
    }
}

class UserContext {
    private ThreadLocal<UInfo> threadLocal;

    private UserContext() {
        this.threadLocal = new ThreadLocal<>();
    }

    public static UserContext getInstance() {
        return SingletonContext.sInstance;
    }

    /**
     * 静态内部类单例模式
     * 单例初使化
     */
    private static class SingletonContext {
        private static final UserContext sInstance = new UserContext();
    }

    public void setContext(UInfo uInfo) {
        threadLocal.set(uInfo);
    }

    public UInfo getContext() {
        return threadLocal.get();
    }

    public void clear() {
        threadLocal.remove();
    }

}

class UInfo {
    String name;
    Integer id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public UInfo(String name, Integer id) {
        this.name = name;
        this.id = id;
    }

}